/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月23日
 */
package com.massyframework.beanskin.util.classloading;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;

/**
 * {@link ClassLoaderUtils}，提供基于类加载器方法的封装.
 * @author  Huangkaihui
 *
 */
public abstract class ClassLoaderUtils {

    /**
     * 将{@code classLoader}设置为当前线程上下文的类加载器，并返回设置前的类加载器
     * @param classLoader {@link ClassLoader},类加载器
     * @return {@link ClassLoader}, 设置前的当前线程上下文的类加载器
     */
    public static ClassLoader setThreadContextClassLoader(ClassLoader classLoader) {
        ClassLoader result = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        return result;
    }

    /**
     * 从{@code classLoader}中加载{@link name}资源流，不使用缓存
     * <p>
     * 对于Fragment应该采用不使用缓存的方式加载资源，否则会导致无法卸载
     * @param name {@link String},资源名称
     * @param classLoader {@link ClassLoader},类加载器
     * @return {@link InputStream}, 输入流
     * @throws IOException 
     */
    public static InputStream getInputStreamWithNotCached(String name, ClassLoader classLoader) throws IOException {
    	Objects.requireNonNull(classLoader, "\"classLoader\" cannot be null.");
    	Objects.requireNonNull(name, "\"name\" cannot be null.");
    	
    	URL url = classLoader.getResource(name);
    	if (url != null) {
    		URLConnection conn = url.openConnection();
    		conn.setUseCaches(false);
    		return conn.getInputStream();
    	}
    	return null;
    }
    
    /**
     * 从{@code url}中加载流，不使用缓存
     * <p>
     * 对于Fragment应该采用不使用缓存的方式加载资源，否则会导致无法卸载
     * @param url {@link URL}
     * @return {@link InputStream}
     * @throws IOException
     */
    public static InputStream getInputStreamWithNotCached(URL url) throws IOException {
    	Objects.requireNonNull(url, "\"url\" cannot be null.");
    	URLConnection conn = url.openConnection();
		conn.setUseCaches(false);
		return conn.getInputStream();
    }
}

